#include "stdafx.h"
#include "StiLib.h"
#include "ColFile.h"

struct ColHeader
{
	char magic[4]; //'C''O''L''\0'
	char Corp[32]; // corpration name
	char lisence[256]; // 

	int count; // count of cols
};
struct ColType
{
	int	 index;  // index of cols from 1~
	char name[256];	// color name
	COLORREF color;	// color in RGB format
};

int LoadColFile(CStiLib* sti, CString fileName)
{
	ColHeader head;
	CFile file;
	file.Open(fileName, CFile::modeRead);
	file.Read(&head, sizeof(ColHeader));

	CString strMagic = "COL";
	if (strMagic != head.magic)
	{
		return -1; // not Col File
	}
	int count = head.count;
	int len = file.GetLength() - sizeof(ColHeader);
	if (count != len/sizeof(ColType))
	{
		return -1; // not valide count;
	}
	ColType* pCols = new ColType [count];
	file.Read(pCols, len);
	ColType* pCol = pCols;
	
	for (int i=0; i<count; i++)
	{
		FLOSS* floss = new FLOSS();
		floss->index = pCol->index;
	//	floss-> = pCol->name;
		floss->color = pCol->color;

		sti->GetFlosses()->AddFloss(floss);

		pCol++;
	}
	delete [] pCols;
	pCols = NULL;
	return 0;
}

int WriteColFile(CStiLib* sti, CString file)
{
	ColHeader head = 
	{
		"COL", "Not yet!", "copy right: xlz@xuluzhu\r\nthanks all.", 0
	};
	head.count = sti->GetFlosses()->GetCount();
	CFile f;
	f.Open(file, CFile::modeWrite|CFile::modeCreate);
	f.Write(&head, sizeof(ColHeader));

	ColType ct = {0};
	FLOSS* pFloss = NULL;

	POSITION pos = sti->GetFlosses()->GetFlossList()->GetHeadPosition();
	while (pos)
	{
		pFloss = sti->GetFlosses()->GetFlossList()->GetNext(pos);
		ct.index = pFloss->index;
		ct.color = pFloss->color;
		f.Write(&ct, sizeof(ColType));
	}

	return 0;
}

//////////// CCoFile class //////////////////

CColFile::CColFile(void)
{
}

CColFile::~CColFile(void)
{
}
